/**
 * @Project： Lqyd_Android
 * @Title：BoutiquePage
 * @Description：
 * @Author：wayne
 * @Date：2014年8月11日上午10:42:19
 */
package com.shwread.android.ui.page;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.humanres.activity.ResMoreActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.OrderMenuMyCouponActivity;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.widget.slideview.ListViewCompat;
import com.shwread.android.ui.widget.slideview.SlideView;
import com.shwread.android.ui.widget.slideview.SlideView.OnSlideListener;
import com.shwread.http.ActionHelp;
import com.shwread.http.base.EmptyHttpResponseHandler;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryMsgsByPositionAction;
import com.shwread.httpsdk.http.face.QryUnReadTotalAction;
import com.tgx.tina.android.ipc.framework.IUIPage;

import java.util.ArrayList;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.MessageBean;
import logic.bean.MessageInfo;
import logic.constants.DefaultConsts;
import logic.util.DateUtil;
import logic.util.PicassoUtil;
import logic.util.Util;


/**
 * @Project： Lqyd_Android
 * @Title：BoutiquePage
 * @Description：消息中心页面
 * @Author：wayne
 * @Date：2014年8月11日上午10:42:19
 */
public class MessagePage
        extends
        AbstractUIPage<MainActivity>
        implements
        OnClickListener,
        OnItemClickListener,
        OnSlideListener
{
	/** 企业消息默认页数 */
	private static int         DEFAULT_PAGENUM_E      = 1;
	/** 系统消息默认页数 */
	private static int         DEFAULT_PAGENUM_S      = 1;
	/** 企业消息未读总条数 */
	private static Integer     UNREAD_MESSAGE_COUNT_E = null;
	/** 系统消息未读总条数 */
	private static Integer     UNREAD_MESSAGE_COUNT_S = null;
	private static int         DEFAULT_PAGELENGTH     = 2000;
	
	private TextView           tvTitle, leftText, leftCount, rightText, rightCount;
	//	private ImageView             ivPersion;
	private Button             ivBack;
	private View               leftView, rightView, emptyView, bodyView, msgLayouView;
	private List<MessageInfo>  enterpriseMessage, systemMessage;
	private Adapter            adapter;
	/** true:当前为企业消息页面，false:当前为系统消息页面 */
	private static boolean     isEnterprise           = true;
	
	private View               loadingView;
	private ImageView          loadingImg;
	private AnimationDrawable  animationDrawable;
	/** 标示第一次进来数据是否加载完成 */
	private Boolean            isLoadEnterprise       = null, isLoadSystem = null;
	/** 判断最后一次数据加载是否成功，不成功的话每次进入此页面需要显示加载动画 */
	private boolean            isLastSuccess          = false;
	private static MessagePage instance;
	
	private ListViewCompat     lv;
	private SlideView          mLastSlideViewWithStatusOn;
	
	public static MessagePage getInstance(MainActivity t) {
		if (instance == null) instance = new MessagePage(t);
		return instance;
	}
	
	public MessagePage(MainActivity t) {
		super(t);
	}
	
	@Override
	public <E extends Activity> View createView(E arg0, int arg1) {
		if (null != curMyView) return curMyView;
		
		curMyView = bActivity.getLayoutInflater().inflate(R.layout.message_lay, null);
		isEnterprise = true;
		initView();
		setListener();
		return curMyView;
	}
	
	void initView() {
		enterpriseMessage = new ArrayList<MessageInfo>();
		systemMessage = new ArrayList<MessageInfo>();
		tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
		tvTitle.setText(  bActivity.getResources().getString(R.string.maintab_message));
		//		ivPersion = (ImageView) curMyView.findViewById(R.id.common_header_persion);
		//		ivPersion.setVisibility(View.VISIBLE);
		ivBack = (Button) curMyView.findViewById(R.id.common_header_back);
		ivBack.setVisibility(View.VISIBLE);
		lv = (ListViewCompat) curMyView.findViewById(R.id.message_listview);
		msgLayouView = curMyView.findViewById(R.id.message_layout);
		loadingView = curMyView.findViewById(R.id.common_loading_layout);
		loadingImg = (ImageView) curMyView.findViewById(R.id.common_loading__img);
		
		leftText = (TextView) curMyView.findViewById(R.id.message_top_left_text);
		leftCount = (TextView) curMyView.findViewById(R.id.message_top_left_count);
		rightText = (TextView) curMyView.findViewById(R.id.message_top_right_text);
		rightCount = (TextView) curMyView.findViewById(R.id.message_top_right_count);
		leftView = curMyView.findViewById(R.id.message_top_left);
		rightView = curMyView.findViewById(R.id.message_top_right);
		bodyView = curMyView.findViewById(R.id.message_body);
		emptyView = curMyView.findViewById(R.id.message_body_empty);
	}
	
	void setListener() {
		//		ivPersion.setOnClickListener(this);
		ivBack.setOnClickListener(this);
		leftView.setOnClickListener(this);
		rightView.setOnClickListener(this);
		
		adapter = new Adapter();
		lv.setAdapter(adapter);
		lv.setOnItemClickListener(this);
	}
	
	private class Adapter
	        extends
	        BaseAdapter
	{
		
		private LayoutInflater mInflater;
		
		Adapter() {
			mInflater = bActivity.getLayoutInflater();
		}
		
		List<MessageInfo> currData = new ArrayList<MessageInfo>();
		
		public void setCurrData(List<MessageInfo> currData) {
			this.currData = currData;
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return currData.size();
		}
		
		@Override
		public Object getItem(int arg0) {
			return currData.get(arg0);
		}
		
		@Override
		public long getItemId(int arg0) {
			return arg0;
		}
		
		@Override
		public View getView(final int position, View view, ViewGroup arg2) {
			ViewHolder holder;
			SlideView slideView = (SlideView) view;
			if (slideView == null)
			{
				View itemView = mInflater.inflate(R.layout.list_item, null);
				
				slideView = new SlideView(bActivity);
				slideView.setContentView(itemView);
				
				holder = new ViewHolder(slideView);
				slideView.setOnSlideListener(MessagePage.this);
				slideView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) slideView.getTag();
			}
			final MessageInfo info = currData.get(position);
			info.setSlideView(slideView);
			info.getSlideView().shrink();
			
			PicassoUtil.load(context, info.getMsgImgUrl(), R.drawable.message_default_icon, holder.img);

			holder.unreadImg.setVisibility(info.getIsRead().toLowerCase().equals("n") ? View.VISIBLE : View.GONE);
			holder.title.setText(info.getTitle());
			holder.time.setText(DateUtil.getShortTime(info.getSendStartTime()));
			holder.content.setText(info.getShortMsg());
			holder.deleteHolder.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View arg0) {
					delMsg(info);
					//					System.out.println("当前要删除的position:"+position);
					//					System.out.println("删除前的数据:"+currData.size()+","+currData.toString());
					currData.remove(position);
					//					System.out.println("删除后的数据:"+currData.size()+","+currData.toString());
					notifyDataSetChanged();
					if (isEnterprise)
					{
						enterpriseMessage = currData;
					}
					else
					{
						//						System.out.println("删除前的systemMessage数据:"+systemMessage.size()+","+systemMessage.toString());
						systemMessage = currData;
						//						System.out.println("删除后的systemMessage数据:"+systemMessage.size()+","+systemMessage.toString());
					}
				}
			});
			return slideView;
		}
	}
	
	private final class ViewHolder
	{
		ImageView img;
		ImageView      unreadImg;
		TextView       title, time, content;
		View           deleteHolder;
		
		ViewHolder(View view) {
			img = (ImageView) view.findViewById(R.id.message_item_img);
			unreadImg = (ImageView) view.findViewById(R.id.message_item_img_flag);
			title = (TextView) view.findViewById(R.id.message_item_title);
			content = (TextView) view.findViewById(R.id.message_item_content);
			time = (TextView) view.findViewById(R.id.message_item_time);
			deleteHolder = view.findViewById(R.id.delete);
		}
	}
	
	@Override
	public int enter(IUIPage<?> arg0) {
		if (!isLastSuccess)
		{
			updateLoadingView(0);
		}
		initData();
		return 0;
	}
	
	@Override
	public void notifyView(int arg0, Bundle arg1) {
		switch (arg0) {
			case DefaultConsts.MESSAGE_REFRESH_CODE:
			case DefaultConsts.PAGE_ONRESUME_CODE:
				System.out.println("收到数据刷新通知！！！");
				initData();
				break;
		}
	}
	
	private int num = 0;
	
	private void initData() {
		if (num <= 0)
		{
			num = 4;
			//获取未读消息总条数
			new QryUnReadTotalAction(bActivity, DefaultConsts.TYPE_WRITESOURCE_ENTERPRISE, new GetUnreadAction(true)).start();
			new QryUnReadTotalAction(bActivity, DefaultConsts.TYPE_WRITESOURCE_SYSTEM, new GetUnreadAction(false)).start();
			//获取消息数据
			new QryMsgsByPositionAction(bActivity, DefaultConsts.TYPE_POSITION_MESSAGECENTER, DefaultConsts.TYPE_WRITESOURCE_ENTERPRISE, DEFAULT_PAGENUM_E, DEFAULT_PAGELENGTH, new GetMsgAction(true)).start();
			new QryMsgsByPositionAction(bActivity, DefaultConsts.TYPE_POSITION_MESSAGECENTER, DefaultConsts.TYPE_WRITESOURCE_SYSTEM, DEFAULT_PAGENUM_S, DEFAULT_PAGELENGTH, new GetMsgAction(false)).start();
		}
	}
	
	private void updateUI() {
		num--;
		if (num > 0) return;
		bActivity.getUIHandler().post(new Runnable()
		{
			@Override
			public void run() {
				messageUnReadChange();
				updateUnreadCount();
				updateTopView();
				showView();
			}
		});
	}
	
	private class GetUnreadAction
	        extends
	        BaseAction
	{
		boolean flag;
		
		public GetUnreadAction(boolean flag) {
			this.flag = flag;
		}
		
		@Override
		public void OK(Object obj) {
			final int count = (Integer) obj;
			if (flag)
			{
				UNREAD_MESSAGE_COUNT_E = count;
			}
			else
			{
				UNREAD_MESSAGE_COUNT_S = count;
			}
			System.out.println("---obj:" + obj);
			System.out.println("---UNREAD_MESSAGE_COUNT_E:" + UNREAD_MESSAGE_COUNT_E);
			System.out.println("---UNREAD_MESSAGE_COUNT_S:" + UNREAD_MESSAGE_COUNT_S);
			updateUI();
		}
		
		@Override
		protected void onError() {
			super.onError();
			updateUI();
		}
	}
	
	private void messageUnReadChange() {
		Message msg = new Message();
		msg.what = DefaultConsts.MESSAGE_UNREAD_CHANGE_CODE;
		Bundle b = new Bundle();
		b.putBoolean("result", (UNREAD_MESSAGE_COUNT_E != null && UNREAD_MESSAGE_COUNT_S != null && (UNREAD_MESSAGE_COUNT_E > 0 || UNREAD_MESSAGE_COUNT_S > 0)) ? true : false);
		msg.setData(b);
		bActivity.getUIHandler().sendMessage(msg);
	}
	
	private void updateUnreadCount() {
		//		leftCount.setText("99");
		//		leftCount.setVisibility(View.VISIBLE);
		//		rightCount.setText("99+");
		//		rightCount.setVisibility(View.VISIBLE);
		if (UNREAD_MESSAGE_COUNT_E != null && UNREAD_MESSAGE_COUNT_S != null)
		{
			leftCount.setText(UNREAD_MESSAGE_COUNT_E < 100 ? String.valueOf(UNREAD_MESSAGE_COUNT_E) : "99+");
			leftCount.setVisibility(UNREAD_MESSAGE_COUNT_E < 1 ? View.GONE : View.VISIBLE);
			rightCount.setText(UNREAD_MESSAGE_COUNT_S < 100 ? String.valueOf(UNREAD_MESSAGE_COUNT_S) : "99+");
			rightCount.setVisibility(UNREAD_MESSAGE_COUNT_S < 1 ? View.GONE : View.VISIBLE);
			
		}
	}
	
	private void delMsg(MessageInfo info) {
		if (info.getIsRead().toLowerCase().equals("n"))
		{
			if (isEnterprise) --UNREAD_MESSAGE_COUNT_E;
			else --UNREAD_MESSAGE_COUNT_S;
			updateUnreadCount();
		}
		//		new DelMsgBySendIdAction(bActivity, String.valueOf(info.getMsgViewId()), new EmptyAction()).start();
		ActionHelp.delMsgBySendId(bActivity, String.valueOf(info.getMsgViewId()), new EmptyHttpResponseHandler());
	}
	
	private MessageInfo readMsg(int position, MessageInfo info) {
		if (info.getIsRead().toLowerCase().equals("n"))
		{
			//			new ReadMsgBySendIdAction(bActivity, String.valueOf(info.getMsgViewId()), new EmptyAction()).start();
			ActionHelp.readMsgBySendId(bActivity, String.valueOf(info.getMsgViewId()), new EmptyHttpResponseHandler());
			if (isEnterprise) --UNREAD_MESSAGE_COUNT_E;
			else --UNREAD_MESSAGE_COUNT_S;
			updateUnreadCount();
			
			info.setIsRead("y");
			if (isEnterprise) enterpriseMessage.set(position, info);
			else systemMessage.set(position, info);
			adapter.setCurrData(isEnterprise ? enterpriseMessage : systemMessage);
		}
		messageUnReadChange();
		return info;
	}
	
	/**
	 * 请求下一页数据（分页）
	 */
	private void getNextPageData() {
		String source = DefaultConsts.TYPE_WRITESOURCE_ENTERPRISE;
		int pageNum = 1;
		if (isEnterprise)
		{
			++DEFAULT_PAGENUM_E;
			pageNum = DEFAULT_PAGENUM_E;
		}
		else
		{
			source = DefaultConsts.TYPE_WRITESOURCE_SYSTEM;
			++DEFAULT_PAGENUM_S;
			pageNum = DEFAULT_PAGENUM_S;
		}
		new QryMsgsByPositionAction(bActivity, DefaultConsts.TYPE_POSITION_MESSAGECENTER, source, pageNum, DEFAULT_PAGELENGTH, new GetMsgAction(isEnterprise)).start();
	}
	
	private class GetMsgAction
	        extends
	        BaseAction
	{
		boolean flag;
		
		public GetMsgAction(boolean flag) {
			this.flag = flag;
		}
		
		@Override
		protected void onError() {
			super.onError();
			if (flag)
			{
				isLoadEnterprise = false;
			}
			else
			{
				isLoadSystem = false;
			}
			updateUI();
		}
		
		@Override
		public void OK(Object obj) {
			if (obj == null) return;
			final MessageBean msg = (MessageBean) obj;
			if (msg.getColumns() == null) return;
			//TODO  实现分页后需要打开注释
			//			if(flag){
			//				enterpriseMessage.addAll(msg.getColumns());
			//			}else{
			//				systemMessage.addAll(msg.getColumns());
			//			}
			if (flag)
			{
				isLoadEnterprise = true;
				enterpriseMessage = msg.getColumns();
			}
			else
			{
				isLoadSystem = true;
				systemMessage = msg.getColumns();
			}
			
			updateUI();
		}
	}
	
	private void showView() {
		if (isLoadEnterprise != null && isLoadSystem != null)
		{
			if (isLoadEnterprise && isLoadSystem)
			{
				isLastSuccess = true;
				updateLoadingView(1);
			}
			else
			{
				isLastSuccess = false;
				updateLoadingView(1);
			}
		}
	}
	
	@Override
	public int leave(IUIPage<?> arg0) {
		return 0;
	}
	
	@Override
	public void setStatus(int arg0) {
		
	}
	
	@Override
	public View updateView(int arg0, ITaskResult arg1) {
		return null;
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		//			case R.id.common_header_persion:
		//				bActivity.goPersonalActivity();
		//				break;
			case R.id.common_header_back:
				bActivity.finish();
				break;
			case R.id.message_top_left:
				isEnterprise = true;
				updateTopView();
				break;
			case R.id.message_top_right:
				isEnterprise = false;
				updateTopView();
				break;
			default:
				break;
		}
	}
	
	void doMessageDetail(MessageInfo info) {
		if (Util.isNotEmpty(info.getAddressUrl()))
		{
			bActivity.goWebViewActivity(info);
		}
		else
		{
			switch (info.getMsgType()) {
				case MessageInfo.TYPE_SYSTEM:
					bActivity.goSystemNotiActivity(info);
					break;
				case MessageInfo.TYPE_BOOK:
					bActivity.goBookDetailActivity(info.getBooks());
					break;
				case MessageInfo.TYPE_LIVES:
				case MessageInfo.TYPE_URL:
					bActivity.goWebViewActivity(info);
					break;
				case MessageInfo.TYPE_ORDER:
//					bActivity.startActivity(new Intent(bActivity, MyAppointmentListActivity.class));
					break;
				case MessageInfo.TYPE_COUPON:
					bActivity.startActivity(new Intent(bActivity, OrderMenuMyCouponActivity.class));
					break;
				case MessageInfo.TYPE_QINGJIA:// 请假提醒
					bActivity.goResMoreActivity("请假管理");
					//notificationIntent.setClass(context, ResMoreActivity.class);
					//notificationIntent.putExtra("title", "请假管理");
					//notificationIntent.putExtra("push", true);
					break;
				case MessageInfo.TYPE_CHUCAI:// 出差提醒
					bActivity.goResMoreActivity("出差管理");
					//notificationIntent.setClass(context, ResMoreActivity.class);
					//notificationIntent.putExtra("title", "出差管理");
					//notificationIntent.putExtra("push", true);
					break;
				case MessageInfo.TYPE_JIABAN:// 加班提醒
					bActivity.goResMoreActivity("加班管理");
					//notificationIntent.setClass(context, ResMoreActivity.class);
					//notificationIntent.putExtra("title", "加班管理");
					//notificationIntent.putExtra("push", true);
					break;
				default:
					break;
			}
		}
	}
	
	private void updateTopView() {
		leftText.setTextColor(bActivity.getResources().getColor(isEnterprise ? R.color.common_white : R.color.common_black));
		rightText.setTextColor(bActivity.getResources().getColor(!isEnterprise ? R.color.common_white : R.color.common_black));
		leftView.setBackgroundResource(isEnterprise ? R.drawable.message_left_check : R.drawable.message_left_uncheck);
		rightView.setBackgroundResource(!isEnterprise ? R.drawable.message_right_check : R.drawable.message_right_uncheck);
		bodyView.setVisibility(View.VISIBLE);
		emptyView.setVisibility(View.GONE);
		if (isEnterprise && enterpriseMessage.size() > 0)
		{
			adapter.setCurrData(enterpriseMessage);
		}
		else if (!isEnterprise && systemMessage.size() > 0)
		{
			adapter.setCurrData(systemMessage);
		}
		else
		{
			bodyView.setVisibility(View.GONE);
			emptyView.setVisibility(View.VISIBLE);
		}
	}
	
	/**
	 * @param flag
	 *            0:加载中，1：加载完成，-1：加载失败
	 */
	private void updateLoadingView(int flag) {
		switch (flag) {
			case 0:
				loadingView.setVisibility(View.VISIBLE);
				msgLayouView.setVisibility(View.GONE);
				loadingImg.setBackgroundResource(R.anim.round_progress);
				animationDrawable = (AnimationDrawable) loadingImg.getBackground();
				animationDrawable.start();
				break;
			case 1:
				if (animationDrawable != null && animationDrawable.isRunning())
				{
					animationDrawable.stop();
				}
				loadingView.setVisibility(View.GONE);
				msgLayouView.setVisibility(View.VISIBLE);
				break;
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		final MessageInfo info = isEnterprise ? enterpriseMessage.get(position) : systemMessage.get(position);
		doMessageDetail(readMsg(position, info));
	}
	
	@Override
	public void onSlide(View view, int status) {
		if (mLastSlideViewWithStatusOn != null && mLastSlideViewWithStatusOn != view)
		{
			mLastSlideViewWithStatusOn.shrink();
		}
		
		if (status == SLIDE_STATUS_ON)
		{
			mLastSlideViewWithStatusOn = (SlideView) view;
		}
	}
}
